import { produce } from 'immer';

type RowItem = {
  id: number;
  content: string;
  author: string;
  imgUrl: string;
};
type ColumnItem = {
  id: number;
  content: string;
  rowIds: string[];
};

type Rows = {
  [k in string]: RowItem;
};
type Columns = {
  [k in string]: ColumnItem;
};

export type InitValues = {
  rows: Rows;
  columns: Columns;
  columnIds: string[];
};

// 同列拖拽
export type DragRowSame = {
  columnId: string;
  rowIds: string[];
};

// 不同列拖拽
export type DragRowDiff = {
  columnId: string[];
  rowIds: string[][];
};

export type DropDragAction =
  | {
      type: '/drop-drag';
      payload: InitValues;
    }
  | {
      type: '/drag-column';
      payload: string[];
    }
  | {
      type: '/drag-row-same';
      payload: DragRowSame;
    }
  | {
      type: '/drag-row-diff';
      payload: DragRowDiff;
    };

const initData = {
  rows: {},
  columns: {},
  columnIds: [],
} as InitValues;

const dropDragReducer = (state = initData, action: DropDragAction) => {
  switch (action.type) {
    case '/drop-drag':
      return action.payload;
    case '/drag-column':
      return produce(state, (draft) => {
        draft.columnIds = action.payload;
      });
    case '/drag-row-same':
      const { rowIds, columnId } = action.payload;
      return produce(state, (draft) => {
        draft.columns[columnId].rowIds = rowIds;
      });
    case '/drag-row-diff':
      const {
        columnId: [startId, endId],
        rowIds: [startRowIds, endRowIds],
      } = action.payload;
      return produce(state, (draft) => {
        draft.columns[startId].rowIds = startRowIds;
        draft.columns[endId].rowIds = endRowIds;
      });
    default:
      return state;
  }
};

export default dropDragReducer;
